package com.haople.sso.web.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.haople.sso.core.authentication.TicketAuthorization;
import com.haople.sso.core.authentication.UserAuthorization;
import com.haople.sso.core.service.CookieService;
import com.haople.sso.core.vo.Ticket;
import com.haople.sso.web.service.UserTicketService;

@Controller
public class LoginController {

	private static final Logger logger=Logger.getLogger(LoginController.class);
	private static final String LOGIN_ERROR_MSG="login_error_msg";
	private static final String ERROR_MSG="error_msg";
	private static final String SSO_CAPTCHA="sso_captcha";
	
	@Autowired
	private TicketAuthorization ticketAuthorization;
	@Autowired
	private UserAuthorization  userAuthorization;
	
	@Autowired
	private UserTicketService userTicketService;
	@Autowired
	private CookieService cookieService;
	
	/**
	 * 进入登录页面
	 * @param request
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "/")
	public String index(String service, HttpServletRequest request, RedirectAttributes redirectAttributes,
			Model model){
		try {
			Cookie[] cookies=request.getCookies();
			Ticket ticket;
			//如果有票据就直接跳转到成功页跳转
			if((ticket=cookieService.getTicket(cookies))!=null && ticketAuthorization.authorization(ticket)){
				logger.info("----检测用户已经登录---[-"+ticket+"-]----");
				//给成功页指定跳转的页面
			    redirectAttributes.addAttribute("callback", service);
				return "redirect:/login-success";
			}
			model.addAttribute("service",service);
			return "login";
		} catch (Exception e) {
			logger.error("--------进入首页异常------跳转登录页--", e);
			redirectAttributes.addFlashAttribute(ERROR_MSG, "系统错误");
			redirectAttributes.addAttribute("service",service);
			return "redirect:/error";
		}
	}
	
	/**
	 *  请求登录
	 * @param userName
	 * @param password
	 * @param service 成功后跳转的页面
	 * @param request
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(String userName, String password, String service, String captcha,
			RedirectAttributes redirectAttributes, HttpSession httpSession) {
		try {
			if(StringUtils.isEmpty(userName)){
				redirectAttributes.addFlashAttribute(LOGIN_ERROR_MSG, "用户名为空！");
				redirectAttributes.addAttribute("service",service);
				return "redirect:/";
			}
			if(StringUtils.isEmpty(password)){
				redirectAttributes.addFlashAttribute(LOGIN_ERROR_MSG, "密码为空！");
				redirectAttributes.addAttribute("service",service);
				return "redirect:/";
			}
			if(StringUtils.isEmpty(captcha)){
				redirectAttributes.addFlashAttribute(LOGIN_ERROR_MSG, "验证码为空！");
				redirectAttributes.addAttribute("service",service);
				return "redirect:/";
			}
			String sessionCaptcha;
			if(StringUtils.isEmpty((sessionCaptcha=String.valueOf(httpSession.getAttribute(SSO_CAPTCHA)))) || !captcha.toLowerCase().equals(sessionCaptcha.toLowerCase())){
				redirectAttributes.addFlashAttribute(LOGIN_ERROR_MSG, "验证码错误！");
				redirectAttributes.addAttribute("service",service);
				return "redirect:/";
			}
			String userId;
			if((userId=userAuthorization.authorization(userName, password))==null){ //如果用户密码验证不成功
				redirectAttributes.addFlashAttribute(LOGIN_ERROR_MSG, "验证失败！");
				redirectAttributes.addAttribute("service",service);
				return "redirect:/";
			}
			//授权成功 生成票据与用户一起存储
			userTicketService.saveTicket(userName);
			redirectAttributes.addAttribute("k", userId); //给成功也传值用于写入cookies
			//给成功页指定跳转的页面
		    redirectAttributes.addAttribute("callback", service);
			return "redirect:/login-success";
		} catch (Exception e) {
			logger.error("--------登录验证用户异常----------", e);
			redirectAttributes.addFlashAttribute(ERROR_MSG, "用户验证异常");
			return "redirect:/error";
		}
	}
	
	@RequestMapping("/login-success")
	public String LoginSuccess(String callback,Model model,String k,HttpServletRequest request,RedirectAttributes redirectAttributes){
		try {
			Ticket t=ticketAuthorization.get(k);
			model.addAttribute("userKey", k);
			if(t==null){
				Cookie[] cookies=request.getCookies();
				if((t=cookieService.getTicket(cookies))==null || !ticketAuthorization.authorization(t)){ 
					return "redirect:/";
				}
			}
			if(!StringUtils.isEmpty(callback)){
				model.addAttribute("callback", callback);
			}
			return "login-success";
		} catch (Exception e) {
			logger.error("------------跳转/success页面异常--------------", e);
			redirectAttributes.addFlashAttribute(ERROR_MSG, "系统错误");
			return "redirect:/error";
		}
	}
	
	
	@RequestMapping("/error")
	public String failure(){
		return "error";
	}
}
